package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hankcs.hanlp.utility.SentencesUtil;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.lang.reflect.Array;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Transactional
@Service
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
    @Autowired
    private WmNewsMapper wmNewsMapper;
    /**
     * 自媒体文章审核
     * @param id
     */
    @Override
    @GlobalTransactional
    @Async  //表明当前方法是一个异步方法
    public void autoScanWmNews(Integer id) {
        //1.查询自媒体文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (wmNews ==   null){
            throw new RuntimeException("WmNewsAutoScanServiceImpl--文章不存在");
        }
        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())){
            //从内容中提取纯文本和图片
            Map<String,Object> textAndImages = handleTextAndImages(wmNews);
            //自管理的敏感词过滤
            boolean isSensitive = handleSensitiveScan((String) textAndImages.get("content"),wmNews);
            if (!isSensitive)return;

            //2.审核文本内容（阿里云接口）
            boolean isTextScan = handleTextScan((String) textAndImages.get("content"),wmNews);
            if (!isTextScan)return;

            //3.审核图片（阿里云接口）
            boolean isImageScan=handleImageScan((List<String>) textAndImages.get("images"),wmNews);
            if (!isImageScan)return;
            
            //4.审核成功，保存app端的相关文章数据
            ResponseResult responseResult = saveAppArticle(wmNews);
            if (!responseResult.getCode().equals(200)){
                throw new RuntimeException("WmNewsAutoScanServiceImpl--文章审核，保存app端相关文章数据失败");
            }
            //回填articleId
            wmNews.setArticleId((Long) responseResult.getData());
            log.info("文章的id为{}",(Long) responseResult.getData());
            updateWmNews(wmNews,(short)9,"审核成功");
        }
    }
    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;
    /**
     * 自管理敏感词审核
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleSensitiveScan(String content, WmNews wmNews) {
        boolean flag=true;
        //获取所有敏感词
        LambdaQueryWrapper<WmSensitive> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.select(WmSensitive::getSensitives);
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(queryWrapper);
        List<String> sensitiveList = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
        //初始化敏感词库
        SensitiveWordUtil.initMap(sensitiveList);
        //查看文章中是否包含敏感词
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if (map.size()>0){
            updateWmNews(wmNews,(short) 2,"当前文章中存在违规内容"+map);
            flag=false;
        }
        return flag;
    }

    @Autowired  //注入fegin  ---  需要去自媒体的启动类加入 fegin的远程调用注解
    private IArticleClient articleClient;
    @Autowired
    private WmChannelMapper wmChannelMapper;
    @Autowired
    private WmUserMapper wmUserMapper;
    /**
     * 保存app端的相关文章数据
     * @param wmNews
     */
    private ResponseResult saveAppArticle(WmNews wmNews) {
        ArticleDto dto=new ArticleDto();
        //属性拷贝
        BeanUtils.copyProperties(wmNews,dto);
        //设置文章布局
        dto.setLayout(wmNews.getType());
        //设置频道
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if (wmChannel!=null){
            dto.setChannelName(wmChannel.getName());
        }
        //设置作者id和姓名
        dto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if (wmUser!=null){
            dto.setAuthorName(wmUser.getName());
        }
        //必须设置文章的id否则会新建
        if (wmNews.getArticleId()!=null){
            dto.setId(wmNews.getArticleId());
        }
        //创建时间
        dto.setCreatedTime(new Date());
        ResponseResult responseResult = articleClient.saveArticle(dto);
        return responseResult;
    }

    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private Tess4jClient tess4jClient;
    @Autowired
    private GreenImageScan greenImageScan;
    /**
     * 审核图片内容
     * @param images
     * @param wmNews
     * @return
     */
    private boolean handleImageScan(List<String> images, WmNews wmNews) {
        Boolean flag=true;
        log.info("进入到了图片审核-----------------！！！！");
       if (images==null||images.size()==0){
           flag=true;
       }
       List<byte []> imageList=new ArrayList<>();
       //下载图片 minio
       //图片去重
       images=images.stream().distinct().collect(Collectors.toList());
       try{
           for (String image : images) {
               byte[] bytes = fileStorageService.downLoadFile(image);
               //byte数组转 bufferedImage
               ByteArrayInputStream in =new ByteArrayInputStream(bytes);
               BufferedImage bufferedImage = ImageIO.read(in);
               //图片文字信息
               String result = tess4jClient.doOCR(bufferedImage);
               //过滤文字
               boolean isSensitive = handleSensitiveScan(result,wmNews);
               if (!isSensitive){
                   return isSensitive;
               }
               imageList.add(bytes);
           }
       }catch (Exception e){
           e.printStackTrace();
       }
    //TODO   -----这里为方便程序运转暂时去除该段阿里云审核代码 若通过敏感信息自审核就代表通过审核
//        //审核
//        try {
//            //TODO ！！！这里由于未开通阿里云服务 测试默认会报错---跳转到异常
//            Map map = greenImageScan.imageScan(imageList);
//            if (map!=null){
//                //自动审核失败
//                if (map.get("suggestion").equals("block")){
//                    flag=false;
//                    updateWmNews(wmNews, (short) 2, "当前文章中存在违规内容");
//                }
//                //人工审核
//                if (map.get("suggestion").equals("review")){
//                    flag=false;
//                    updateWmNews(wmNews, (short) 3, "当前文章中存在不确定内容");
//                }
//            }
//        } catch (Exception e) {
//            //TODO --- 为了方便测试这里先返回true 图片通过审核
//            //flag=false;
//            flag=true;
//            log.info("模拟审核图片------通过！！！！！");
//            //e.printStackTrace();
//        }
        return flag;
    }

    @Autowired
    private GreenTextScan greentextScan;
    /**
     * 审核纯文本内容
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleTextScan(String content, WmNews wmNews) {
        Boolean flag=true;
        if ((wmNews.getTitle()+"-"+content).length()==0){
            return flag;
        }
        try {
            Map map=greentextScan.greeTextScan(content);
            //TODO 这里由于未注册阿里云服务--导致map始终为空
            int i= 1/0;   //直接抛异常
            if (map!=null){
                //自动审核失败
                if (map.get("suggestion").equals("block")){
                    flag=false;
                    updateWmNews(wmNews, (short) 2, "当前文章中存在违规内容");
                }
                //人工审核
                if (map.get("suggestion").equals("review")){
                    flag=false;
                    updateWmNews(wmNews, (short) 3, "当前文章中存在不确定内容");
                }
            }
        } catch (Exception e) {
            // 正常情况为 flag=false;
            flag=true;
            log.info("模拟审核文本---------通过！！！");
        }
        //TODO 会直接调到这一步 返回结果还是 flag=true
        //测试文本自动审核违规内容----false
        //flag=false;
        //updateWmNews(wmNews, (short) 2, "当前文章中存在违规内容");

        return flag;
    }

    /**
     * 修改文章内容---修改其状态
     * @param wmNews
     * @param status
     * @param reason
     */
    private void updateWmNews(WmNews wmNews, short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    /**
     * 从自媒体文章的内容中提取文章内容与图片
     * 提取文章的封面图片
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        String content = wmNews.getContent();
        //用来存储纯文本内容
        StringBuilder stringBuilder=new StringBuilder();
        //用来存储图片内容地址
        List<String> images=new ArrayList<>();
        if (StringUtils.isNotBlank(content)){
            List<Map> maps = JSON.parseArray(content, Map.class);
            for (Map map : maps) {
                if (map.get("type").equals("text")){
                    stringBuilder.append(map.get("value"));
                }
                if (map.get("type").equals("image")){
                    images.add((String) map.get("value"));
                }
            }
        }
        //提取文章的封面图片
        if (StringUtils.isNotBlank(wmNews.getImages())){
            String[] indexImages = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(indexImages));
        }
        //返回值Map
        Map<String,Object> result=new HashMap<>();
        result.put("content",stringBuilder.toString());
        result.put("images",images);
        return  result;
    }
}
